package com.hb.trans.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import com.hb.trans.bean.GPSDisable
import org.greenrobot.eventbus.EventBus

class LocationMgr private constructor(var mContext: Context) : LocationListener {

    private val TAG = this::class.java.simpleName
    private var lm: LocationManager
    var loc: Location

    private object mHolder {
        fun getNewInstance(context: Context) = LocationMgr(context)
    }

    companion object {
        fun getInstance(context: Context): LocationMgr {
            return mHolder.getNewInstance(context)
        }
    }


    init {
        lm = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        loc = if (ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) ?: Location(LocationManager.NETWORK_PROVIDER)
        } else {
            Location(LocationManager.NETWORK_PROVIDER)
        }
    }

    fun initLocation() {
        if (ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            if (isEnableGps()) {
                lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null)
            } else {
                //无法定位：1、提示用户打开定位服务；2、跳转到设置界面
                EventBus.getDefault().post(GPSDisable(false))
            }
        }
    }


    override fun onLocationChanged(location: Location?) {
        if (location != null) {
            this.loc = location
            EventBus.getDefault().post(location)
        }
    }

    override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {

    }

    override fun onProviderEnabled(provider: String?) {
    }

    override fun onProviderDisabled(provider: String?) {
    }

    private fun isEnableGps(): Boolean {
        return lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    fun destory() {
        lm.removeUpdates(this)
    }
}